package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.Student;
import com.ruoyi.system.mapper.GradesMapper;
import com.ruoyi.system.mapper.StudentMapper;
import com.ruoyi.system.utils.Upload;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ClassesMapper;
import com.ruoyi.system.domain.Classes;
import com.ruoyi.system.service.IClassesService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 班级Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-15
 */
@Service
@Slf4j
public class ClassesServiceImpl implements IClassesService 
{
    @Autowired
    private ClassesMapper classesMapper;

    @Resource
    private GradesMapper gradesMapper;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private SysDeptServiceImpl sysDeptService;

    /**
     * 查询班级
     * 
     * @param cid 班级主键
     * @return 班级
     */
    @Override
    public Classes selectClassesByCid(Long cid)
    {
        return classesMapper.selectClassesByCid(cid);
    }

    /**
     * 查询班级对应学生列表
     */
    @Override
    public List<Map<Classes, List<Student>>> selectOneToMoreClass(Integer gid) {
        List<Classes> classes = classesMapper.selectClassByGid(gid);
        Map<Classes, List<Student>> map = new HashMap<>();
        List<Map<Classes, List<Student>>> studentList = new ArrayList<>();
        for (int i = 0; i < classes.size(); i++) {
            List<Student> selectOneStudent = studentMapper.selectOneStudent(gid, classes.get(i).getCid());
            map.put(classes.get(i), selectOneStudent);
        }
        studentList.add(map);
        return studentList;
    }

    /**
     * 用户上传Excel进行分班
     * 注意：用户更新第四列，也就是属于几班，需要填写数字
     *
     * 在班级管理页面显示班级主键ID当作编号
     * 用户在编辑分班表时，最后一列的属于几班，填写的是班级主键ID
     */
    @Override
    @Transactional
    public String uploadAndUpdateByDivision(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("拿到文件后缀 = " + suffix);
        if (!suffix.equals(".xlsx")) {
            log.error("上传文件失败,请检查格式,文件需为.xlsx类型");
            return "4";
        }

        XSSFWorkbook wb1 = new XSSFWorkbook(file.getInputStream());

        String[][] result = new String[0][];
        try {
            // 获取Excel表文件里的数据
            //第二个参数为从Excel文件里第几行开始读
            result = Upload.getData(wb1, 0);
            if (!result[0][0].equals("学生姓名") || !result[0][1].equals("学生性别") || !result[0][2].equals("身份证号") || !result[0][3].equals("属于几班")) {
                log.error("导入的Excel模板与下载的不匹配,请重新上传");
                return "3";
            }
            for (int i = 0; i < result.length; i++) {
                for (int j = 0; j < result[i].length - 1; j++) {
                    log.info("result[i][j] = " + "result[" + i + "][" + j + "] = " + result[i][j]);
                }
            }
            int len = result.length;
            log.info("result.length = " + len);
            if (len < 0) {
                return "2";
            }
            Integer sidToLoginUser = sysDeptService.getSidToLoginUser();
            log.info("sid = " + sidToLoginUser);
            for (int i = 1; i < result.length; i++) {
                Student student = studentMapper.selectStudentIdToNameAndSid(sidToLoginUser, result[i][0], result[i][2]);
                if (student == null) {
                    log.error("系统中找不到关于 " + result[i][0] + " 的信息,请核对Excel表格");
                    return result[i][0];
                }
                if (result[i][3].isEmpty()) {
                    log.error("Excel表格中不可以出现为空的单元格,请检查");
                    return "5";
                }
                student.setStudentBelongToClass(Long.valueOf(result[i][3]));
                studentMapper.updateStudent(student);
                log.info("第" + i + "条学生分班完成");
            }
            return "1";
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            wb1.close();
        }
        return "0";
    }

    /**
     * 分班
     */
    @Override
    public int division() {
        return 0;
    }

    /**
     * 查询班级列表
     * 
     * @param classes 班级
     * @return 班级
     */
    @Override
    public List<Classes> selectClassesList(Classes classes)
    {
        return classesMapper.selectClassesList(classes);
    }

    /**
     * 新增班级
     * 
     * @param classes 班级
     * @return 结果
     */
    @Override
    public int insertClasses(Classes classes)
    {
        classes.setCreateTime(DateUtils.getNowDate());
        return classesMapper.insertClasses(classes);
    }

    /**
     * 修改班级
     * 
     * @param classes 班级
     * @return 结果
     */
    @Override
    public int updateClasses(Classes classes)
    {
        return classesMapper.updateClasses(classes);
    }

    /**
     * 批量删除班级
     * 
     * @param cids 需要删除的班级主键
     * @return 结果
     */
    @Override
    public int deleteClassesByCids(Long[] cids)
    {
        return classesMapper.deleteClassesByCids(cids);
    }

    /**
     * 删除班级信息
     * 
     * @param cid 班级主键
     * @return 结果
     */
    @Override
    public int deleteClassesByCid(Long cid)
    {
        return classesMapper.deleteClassesByCid(cid);
    }
}
